package com.itcam.tingshu.user.api;

import javax.cache.CacheManager;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * @author : Cammy.Wu
 * Description : CompletableFuture演示
 */

public class DemoCompletableFuture {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // CompletableFuture —— 异步编排
        // 异步编排:开启一个线程执行一个异步相对耗时的任务
        // 如何创建一个CompletableFuture 对象 runAsync();supplyAsync();
        // CompletableFuture<Void> future = CompletableFuture.runAsync(() ->
        //         System.out.println("hello") // hello
        // );
        // 获取这个线程执行的结果
        // System.out.println(future.get()); // null

        // 案例一
        //CompletableFuture<String> futureA = CompletableFuture.supplyAsync(() -> "hello");

        //CompletableFuture<Void> futureB = futureA.thenAcceptAsync(s -> {
        //    try {
        //        Thread.sleep(3000);
        //    } catch (InterruptedException e) {
        //        throw new RuntimeException(e);
        //    }
        //    System.out.println(s + " world");
        //});

        //CompletableFuture<Void> futureC = futureA.thenAcceptAsync(s -> {
        //    try {
        //        Thread.sleep(1000);
        //    } catch (InterruptedException e) {
        //        throw new RuntimeException(e);
        //    }
        //    System.out.println(s + " cammy");
        //});

        //System.out.println(futureA.get());
        //System.out.println(futureB.get());
        //System.out.println(futureC.get());

        // 案例二
        //CompletableFuture<Void> futureA = CompletableFuture.runAsync(() -> {
        //    System.out.println("hello world");
        //});

        //CompletableFuture<Void> futureB = futureA.thenRunAsync(() -> {
        //    System.out.println("cammy");
        //});

        // 案例三
        //CompletableFuture<Integer> supplyAsync = CompletableFuture.supplyAsync(() -> {
        //    int total = 0;
        //    for (int i = 1; i <= 365; i++) {
        //        total += 1;
        //    }
        //    return total;
        //}).thenApplyAsync(t -> {
        //    System.out.println("t = " + t);
        //    return 2 * t;
        //});
        //System.out.println(supplyAsync.get());

        // 案例四
        CompletableFuture<Integer> supplyAsync = CompletableFuture.supplyAsync(() -> {
            int total = 0;
            for (int i = 1; i <= 365; i++) {
                total += i;
            }
            int j = 1 / 0;
            return total;
        }).whenComplete((t, u) -> {
            System.out.println(t); // t —— 66795 —— total —— 上一个线程执行的结果
            System.out.println(u); // u —— / by zero —— 捕获异常
        }).exceptionally(t -> {
            System.out.println(t);
            return 404;
        });
        // 打印数据
        System.out.println(supplyAsync.get());

    }
}
